using System;
using System.Threading.Tasks;
using Dapper;
using hao_Common.Dapper.Db;
using hao_Common.Dapper.Repository;
using hao_Model;

namespace hao_Reppsitory.Product
{
    /// <summary>
    /// 商品留言点赞仓储实现
    /// </summary>
    public class ProductCommentLikeRepository : DapperGenericRepository<ProductCommentLike>, IProductCommentLikeRepository
    {
        public ProductCommentLikeRepository(IDbConnectionFactory connectionFactory) : base(connectionFactory) { }

        /// <summary>
        /// 检查用户是否已点赞留言
        /// </summary>
        public async Task<ProductCommentLike> GetLikeAsync(Guid commentId, Guid userId)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                SELECT * FROM ProductCommentLike
                WHERE CommentId = @CommentId AND UserId = @UserId AND IsDeleted = 0";
            
            return await connection.QuerySingleOrDefaultAsync<ProductCommentLike>(sql, new 
            { 
                CommentId = commentId, 
                UserId = userId 
            });
        }

        /// <summary>
        /// 添加点赞
        /// </summary>
        public async Task<ProductCommentLike> AddLikeAsync(Guid commentId, Guid userId)
        {
            var like = new ProductCommentLike
            {
                Id = Guid.NewGuid(),
                CommentId = commentId,
                UserId = userId,
                CreatedAt = DateTime.UtcNow,
                IsDeleted = false
            };
            
            await AddAsync(like);
            return like;
        }

        /// <summary>
        /// 取消点赞
        /// </summary>
        public async Task<bool> RemoveLikeAsync(Guid commentId, Guid userId)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                UPDATE ProductCommentLike 
                SET IsDeleted = 1 
                WHERE CommentId = @CommentId AND UserId = @UserId AND IsDeleted = 0";
            
            var rowsAffected = await connection.ExecuteAsync(sql, new 
            { 
                CommentId = commentId, 
                UserId = userId 
            });
            
            return rowsAffected > 0;
        }

        /// <summary>
        /// 获取留言的点赞数量
        /// </summary>
        public async Task<int> GetLikeCountAsync(Guid commentId)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                SELECT COUNT(1) FROM ProductCommentLike 
                WHERE CommentId = @CommentId AND IsDeleted = 0";
            
            return await connection.QuerySingleAsync<int>(sql, new { CommentId = commentId });
        }
    }
}